package edu.ccut.saturn.basecomponent.databasecomponent;

import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.basecomponent.database.ISelectSQLBuilder;
import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.ISaturnSQLBuilder;
import edu.ccut.saturn.basecomponent.database.SaturnSQLBuilderFactory;
import edu.ccut.saturn.basecomponent.database.SaturnSQLHandler;
import edu.ccut.saturn.basecomponent.database.util.SaturnDataUtil;
import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameter;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;

public class QueryByPrimaryKey extends DefaultComponent {

	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		debug(Messages.getString("QueryByPrimaryKey.9"), parameterContext); //$NON-NLS-1$

		super.execute(parameterContext);

		String fullKey = (String) parameterContext.getParameterValue(0);

		String primaryKeyValue = (String) parameterContext.getParameterValue(1);

		String dbType = SaturnDataUtil.getStandardDBType(fullKey);

		ISaturnSQLBuilder builder = SaturnSQLBuilderFactory
				.getSaturnSQLBuilder(dbType);

		if (builder != null) {

			String condition = SaturnDataUtil
					.getConditionWithPrimaryKeyByDbType(fullKey,
							primaryKeyValue);

			ISelectSQLBuilder selectSQLBuilder = builder
					.getSelectSQLBuilder(getBuilderType(fullKey));

			ISaturnSQL saturnSQL = selectSQLBuilder.build(fullKey, condition);

			List<SaturnData> list = SaturnSQLHandler.executeQuery(saturnSQL,
					parameterContext.getConnection());

			IParameter parameter = parameterContext.getParameter(2);

			if (ArrayList.class.getName().equals(
					parameter.getClassType().getName())) {
				parameterContext.setParameter(2, list);
			} else {
				if (list == null)
					parameterContext.setParameter(2, null);
				else
					parameterContext.setParameter(2, list.get(0));
			}
		}
	}

	private String getBuilderType(String fullKey) {
		if (SaturnDataUtil.hasLOB(fullKey)) {
			return ISaturnSQL.SELECT_LOB_OPERATION;
		} else {
			return ISaturnSQL.SELECT_OPERATION;
		}
	}
}
